import { prisma } from '../../utils/prisma'
import { assertChildOwnership } from '../../utils/guard'
import { parseLocalDate } from '../../utils/date'
import { z } from 'zod'

export default eventHandler(async (event) => {
  const q = getQuery(event)
  const schema = z.object({ childId: z.string(), date: z.string().optional() })
  const parsed = schema.safeParse(q)
  if (!parsed.success) throw createError({ statusCode: 422, statusMessage: 'INVALID_INPUT' })
  const childId = Number(parsed.data.childId)
  if (!Number.isFinite(childId)) throw createError({ statusCode: 400, statusMessage: 'BAD_ID' })
  await assertChildOwnership(event, childId)

  const records = await prisma.activityRecord.findMany({
    where: {
      childId,
      ...(parsed.data.date ? { date: parseLocalDate(parsed.data.date) } : {})
    },
    orderBy: { id: 'asc' }
  })
  const dayTotal = records.reduce((s, r) => s + r.points, 0)
  return { records, dayTotal }
})


